# coding: utf-8
import json

from PySide6.QtCore import Qt, Signal
from PySide6.QtWidgets import QWidget, QVBoxLayout
from qfluentwidgets import BodyLabel, PlainTextEdit, PrimaryPushButton, setFont

from common import cfg
from components import Alert


class DataInterface(QWidget):
    treeDataSignal = Signal(object)

    def __init__(self, parent=None):
        super().__init__(parent)
        self.verticalLayout = QVBoxLayout(self)
        self.cookieLabel = BodyLabel('Cookie', self)
        self.cookieTextEdit = PlainTextEdit(self)
        self.coursewareTreeLabel = BodyLabel('课程树数据', self)
        self.treeUrlLabel = BodyLabel('https://degree.qingshuxuetang.com/sias/Svc/GetCoursewareTree', self)
        self.coursewareTreeTextEdit = PlainTextEdit(self)
        self.startBtn = PrimaryPushButton('开始解析', self)

        self.treeUrlLabel.setTextInteractionFlags(Qt.TextInteractionFlag.TextSelectableByMouse)
        setFont(self.cookieLabel, 16)
        setFont(self.coursewareTreeLabel, 16)
        setFont(self.treeUrlLabel, 12)

        self.verticalLayout.addWidget(self.cookieLabel, 0)
        self.verticalLayout.addWidget(self.cookieTextEdit, 1)
        self.verticalLayout.addWidget(self.coursewareTreeLabel, 0)
        self.verticalLayout.addWidget(self.treeUrlLabel, 0)
        self.verticalLayout.addWidget(self.coursewareTreeTextEdit, 1)
        self.verticalLayout.addWidget(self.startBtn, 0)

        cookie = cfg.get(cfg.cookie)
        if cookie:
            self.cookieTextEdit.setPlainText(cookie)

        self.startBtn.clicked.connect(self.onStartBtnClicked)

    def onStartBtnClicked(self):
        cookie = self.cookieTextEdit.toPlainText()
        coursewareTreeData = self.coursewareTreeTextEdit.toPlainText()
        if not cookie or not coursewareTreeData:
            Alert.warning('请填写Cookie和课程树数据')
            return
        try:
            treeData = json.loads(coursewareTreeData)
        except json.JSONDecodeError:
            Alert.error('课程树数据格式错误')
            return
        cfg.set(cfg.cookie, cookie)
        self.treeDataSignal.emit(treeData)
